#include "CloudiskServer.h"
#include "CryptoUtil.h"
#include "workflow/MySQLResult.h"
#include "nlohmann/json.hpp"
#include "wfrest/PathUtil.h"
#include "HashUtil.h"
#include "ParseUtil.h"
#include <map>
#include <string>
#include <sstream>
#include <fstream>
using namespace wfrest;
using namespace protocol;
using std::cout;
using std::endl;
using std::map;
using std::string;
using std::istringstream;
using std::ifstream;
using std::ostringstream;

string CloudiskServer::mysql_url = LoadConfig::loadConfig()["MYSQL_URL"];

int CloudiskServer::start(unsigned short int port){
    return m_server.start(port);
}

void CloudiskServer::stop(){
    m_server.stop();
}

void CloudiskServer::list_routes(){
    m_server.list_routes();
}

CloudiskServer& CloudiskServer::track(){
    m_server.track();
    return *this;
}

void CloudiskServer::register_modules(){
    register_static_resources_modules();
    register_signup_modules();
    register_signin_modules();
    register_userinfo_modules();
    register_file_list_modules();
    register_file_upload_modules();
    register_file_download_modules();
}

//注册路由
void CloudiskServer::register_static_resources_modules(){
    m_server.GET("/user/signup", [](const HttpReq *, HttpResp * resp){
        resp->File("static/view/signup.html");
    });

    m_server.GET("/static/view/signin.html", [](const HttpReq *, HttpResp * resp){
        resp->File("static/view/signin.html");
    });

    m_server.GET("/static/view/home.html", [](const HttpReq *, HttpResp * resp){
        resp->File("static/view/home.html");
    });

    m_server.GET("/static/js/auth.js", [](const HttpReq *, HttpResp * resp){
        resp->File("static/js/auth.js");
    });

    m_server.GET("/static/img/avatar.jpeg", [](const HttpReq *, HttpResp * resp){
        resp->File("static/img/avatar.jpeg");
    });

    m_server.GET("/file/upload", [](const HttpReq *, HttpResp * resp){
        resp->File("static/view/index.html");
    });

    m_server.Static("/file/upload_files","static/view/upload_files");
}


//获取用户信息验证token
void CloudiskServer::register_userinfo_modules()
{
    m_server.GET("/user/info", [](const HttpReq *req, HttpResp *resp)
    {
        string url;
        req->get_request_uri(url);
        map<string,string> params = ParseUtil::get_query_param(url);
        string token = params["token"];

        ParseUtil::verify_token(req, resp, [resp,token](User user){
            if(user.id != 0 && CryptoUtil::verify_token(token,user)){
                nlohmann::json retMsg;
                retMsg["data"]["Username"] = user.username;
                retMsg["data"]["SignupAt"] = user.createdAt;
                resp->String(retMsg.dump());
            } else {
                resp->set_status(HttpStatusUnauthorized);
            }
        }); 
    });
}


